package ywpt.core.util;
import java.security.MessageDigest;
public class StringTools {
	public StringTools() {
	}
	public static String md5(String piStr) {
		if (isNullOrSpace(piStr)) {
			piStr = "";
		}
		String encodeStr = "";
		byte digesta[] = null;
		try {
			MessageDigest alg = MessageDigest.getInstance("MD5");
			alg.update(piStr.getBytes());
			digesta = alg.digest();
			encodeStr = byte2hex(digesta);
		} catch (Exception exception) {
		}
		return encodeStr;
	}
	private static String byte2hex(byte piByte[]) {
		String reStr = "";
		@SuppressWarnings("unused")
		String tmpStr = "";
		for (byte element : piByte) {
			int v = element & 0xff;
			if (v < 16) {
				reStr = reStr + "0";
			}
			reStr = reStr + Integer.toString(v, 16).toLowerCase();
		}
		return reStr;
	}
	public static String iso2GB(String str) {
		try {
			if (str != null) {
				str = new String(str.getBytes("ISO-8859-1"), "GB2312");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	public static String gb2ISO(String str) {
		try {
			if (str != null) {
				str = new String(str.getBytes("GB2312"), "ISO-8859-1");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	public static boolean isNullOrSpace(String str) {
		return (str == null) || (str.trim().length() < 1);
	}
	public static final String replace(String mainString, String oldString, String newString) {
		if (mainString == null) {
			return null;
		}
		int i = mainString.lastIndexOf(oldString);
		if (i < 0) {
			return mainString;
		}
		StringBuffer mainSb = new StringBuffer(mainString);
		for (; i >= 0; i = mainString.lastIndexOf(oldString, i - 1)) {
			mainSb.replace(i, i + oldString.length(), newString);
		}
		return mainSb.toString();
	}
	public static final String safeStr(String s) {
		String ret = replace(s, "'", "");
		ret = replace(ret, "\"", "");
		return ret;
	}
	public static final String substring(String s, int start, int end) {
		if (s == null) return null;
		int length = s.length();
		if (end > length) {
			return null;
		}
		return s.substring(start, end);
	}
}
